<template>
  <div class="orderlist">
    <div class="backgroudimage" v-show="backgroundflag" @click="changeshow">
      <img class="ims" src="@/assets/img/background.png" alt />
    </div>
    <van-nav-bar title="首页" @click-right="onClickRight" style="z-index:1001" fixed>
      <span></span>
      <!-- <van-icon
        :name="require('@/assets/img/computer.png')"
        slot="right"
        color="#333"
        size="0.6rem"
      /> -->
    </van-nav-bar>
        <!-- <div class="ordersearch" style="z-index:1001">
          <div class="searchLeft">
            <form action="javascript:return true">
              <van-search
                v-model="value"
                show-action
                placeholder="订单号/客户名称/姓名/手机号/地址"
                @search="onSearch"
                @click="showSearch"
              >
                <div slot="action" @click="onSearch(value)">搜索</div>
              </van-search>
            </form>
          </div>
          <van-icon
            :name="require('@/assets/img/searchIcon.png')"
            slot="right"
            color="#333"
            size="0.44rem"
            class-prefix="menuIcon"
            @click="showSearchItem"
          />
        </div> -->
        <!--筛选项-->

        <div class="lists">
          <van-list v-model="loading" :finished="finished" finished-text="寻找伴侣？点击下方按钮来一场完美的邂逅吧~"  @load="onLoad">
            <van-pull-refresh v-model="isLoading" @refresh="onRefresh" loading-text="即将邂逅您的伴侣~~">
              <van-cell
                class="info"
                v-for="(good,index) in mockArr"
                :key="index"
                v-show="data.totalCount!=0"
              >
                <!-- <div @click="godetail(good.KaOrderId)" class="lsit">
                 
                </div> -->
                <div class="count">
                <div class="times">
                  <p>即将赴约</p>
                </div>
               <div>
                 2021年8月20日 12:00
               </div>
                </div>
               
                 <van-icon @click="concal" size="20px" name="close" />
              </van-cell>
            </van-pull-refresh>
          </van-list>
          <div class="btnes">
            <van-button @click="go" loading-size="30px" color="#55A79A" icon="https://lecarlinkobs2.obs.cn-north-4.myhuaweicloud.com/ka/1428371340074815488.png" type="info">
              寻找伴侣
            </van-button>
          </div>
        <van-cell
                :class="loadflag ? 'info animate__animated animate__flipInX' : 'info animate__animated animate__flipInX'"
                v-show="loadflag"
              >
                <!-- <div @click="godetail(good.KaOrderId)" class="lsit">
                 
                </div> -->
                <div class="count" >
                <div class="times">
                  <p>新的邂逅</p>
                </div>
               <div>
                 {{cont}}
               </div>
                </div>
               <van-icon  @click="like" v-show="!likeFlag" name="like-o" size="20px"/>
               <van-icon  v-show="likeFlag" name="like" size="20px" color="red" />
              </van-cell>
        </div>
         <van-tabbar v-model="active" active-color="#42b983" inactive-color="#000">
      <van-tabbar-item @click="router('/orderlist')" icon="wap-home-o"
        >首页</van-tabbar-item
      >
      <van-tabbar-item @click="router('/my')" icon="contact"
        >我的</van-tabbar-item
      >
    </van-tabbar>
        <van-calendar v-model="datashow" title="赴宴日期" @confirm="onConfirm" color="#55A79A" @unselect="dataclose"  />
        <van-popup v-model="showPicker" position="bottom">
          <van-datetime-picker
            title="赴宴时间"
            min-hour="10"
            max-hour="21"
            type="time"
            @confirm="ontimerConfirm"
            @cancel="dataclose"
          />
        </van-popup>
  </div>
</template>
<script>
import Vue from "vue";
import { orderlist } from "@/api/orderlist";
import { pushOrderNotice } from "@/api/orderlist";

import {
  Icon,
  Field,
  Button,
  Image,
  Search,
  Toast,
  List,
  Checkbox,
  SubmitBar,
  Popup,
  Col,
  Row,
  Calendar,
  PullRefresh,
  Tab,
  DatetimePicker,
  Tabs
} from "vant";
import { Dialog } from "vant";
import { createsharelist } from "@/api/sharelist";
import { share } from "@/api/orderlist";
import { formatDate } from "@/utils/utils";
Vue.use(Icon);
Vue.use(Field);
Vue.use(Button);
Vue.use(Image);
Vue.use(DatetimePicker);
Vue.use(Search);
Vue.use(Toast);
Vue.use(List);
Vue.use(Checkbox);
Vue.use(SubmitBar);
Vue.use(Popup);
Vue.use(Col);
Vue.use(Row);
Vue.use(Calendar);
Vue.use(PullRefresh);
Vue.use(Tab);
Vue.use(Tabs);
export default {
  data() {
    return {
      mockArr:[1,2,3],
      value: "",
      loading: false,
      isLoading: false,
      likeFlag: false,
      finished: true,
      currentPage: 1,
      pagecount: 1,
      showPicker: false,
      pageSize: 5,
      data: [],
      num: 0,
      active:0,
      loadflag: false,
      serachTxt: "",
      isshowSearch: false,
      flag: false,
      checked: false,
      idlist: [],
      shownums: 0,
      pricesum: 0,
      backgroundflag: false,
      datashow: false,
      username: "",
      IsshowSearchItem: false,
      isActice: true,
      isShowCalendar: false,
      minDate: new Date(2000, 0, 1),
      maxDate: new Date(),
      defaultDate: new Date(),
      cont:"在北京寻找爱情",
      contarr: ['在北京寻找爱情','一场浪漫的邂逅','寻找一个家','想找一个可以一起吃饭的人'],
      orderType: [
        {
          text: "全部",
          value: null,
          active: true
        },
        {
          text: "四通易达",
          value: 1,
          active: false
        },
        {
          text: "易达货运",
          value: 2,
          active: false
        }
      ],
      payType: [
        {
          text: "全部",
          value: null,
          active: true,
          offset: 0
        },
        {
          text: "待支付",
          value: 1,
          active: false,
          offset: 0
        },
        {
          text: "部分支付",
          value: 2,
          active: false,
          offset: 0
        },
        {
          text: "已支付",
          value: 3,
          active: false,
          offset: 8
        },
        {
          text: "未到账期",
          value: 4,
          active: false,
          offset: 0
        }
      ],
      startDate: null,
      endDate: null,
      chooseDateType: "startDate"
    };
  },
  created(){
  },
  mounted() {
    sessionStorage.clear();
    this.getorderlist();
  },
  methods: {
    onSearch(val) {
      this.serachTxt = val;
      this.isshowSearch = false;
      // this.finished = false;
      this.num = 1;
      // if (this.serachTxt == '') {
      //   this.$toast('搜索关键词不能为空');
      // } else {
      this.getorderlist();
      // }
    },
    like(){
      this.datashow = true
    },
    onConfirm(){
      this.datashow = false
      this.showPicker = true
    },
    dataclose(){
      this.likeFlag = false
      this.showPicker = false
    },
    ontimerConfirm(){
      Toast({
        message: '邀请已发送！',
        icon: 'like',
        color:'red'
      });
      this.likeFlag = true

      this.showPicker = false

          },
    onChange(val) {
      if( val == 1) {
        this.num = 0;
        this.flag = true;
        this.getorderlist();
      } else if (val == 0){
        this.num = 0;
        this.flag = false;
        this.getorderlist();
      }
    },
    go(){
      this.loadflag = false
      this.cont = this.contarr[Math.floor(Math.random()*4)]
      Toast.loading({
  message: '加载中...',
  forbidClick: true,
});
  setTimeout(() => {
    this.likeFlag = false
    this.loadflag = true
    }, 2000);
  },
    concal(){
      Dialog.confirm({
  title: '确定取消赴约吗？',
  message: '',
})
  .then(() => {
    // on confirm
    Toast.success('取消成功');
  })
  .catch(() => {
    // on cancel
  });
    },
    changeshow() {
      this.backgroundflag = false;
    },
    wechatShare(id) {
      // 判断苹果手机
      let url = window.location.href.split("#")[0];

      console.log(`Share init urls = ${url}`);

      let that = this;

      url = encodeURIComponent(url);

      //这里是封装的axios，换成任意请求皆可
      share(url).then(res => {
        wx.config({
          // 配置信息, 即使不正确也能使用 wx.ready
          debug: false,
          appId: res.data.appid,
          timestamp: res.data.timestamp,
          nonceStr: res.data.noncestr,
          signature: res.data.sign,
          jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"]
        });
        wx.ready(function() {
          //需在用户可能点击分享按钮前就先调用
          console.log("初始化成功");
          let wxData = {
            title: "四通易达", // 分享标题
            desc: `您的好友${that.username}向您发起一笔收款，请及时支付`, // 分享描述
            link: Vue.prototype.$conf.domainname + `/?#/receivables?id=${id}`,
            imgUrl:
              "https://lecarlinkoss.oss-cn-beijing.aliyuncs.com/media/wx/zt/hz/4c53c879309e46ba89dd3cd7fa0d7e43.png", // 分享图标
            success: function() {
              console.log("设置成功");
              this.backgroundflag = true;
            },
            fail: function(err) {
              console.log("设置失败" + JSON.stringify(err));
              alert(`分享设置失败: ${JSON.stringify(err)}`);
              this.backgroundflag = true;
            }
          };

          wx.updateAppMessageShareData(wxData);
          wx.updateTimelineShareData(wxData);
        });
        wx.error(function(err) {
          console.log(err);
          alert(`微信配置初始化失败: ${JSON.stringify(err)}`);
        });
      });
      this.backgroundflag = true;
    },

    shareprice() {
      let iswx = (function() {
        return (
          navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1
        );
      })();

      if (iswx) {
        let ids = this.idlist.map(item => {
          return item.KaOrderId;
        });

        createsharelist(ids).then(res => {
          if (res.code == 200) {
            this.username = res.data.shareName;
            this.wechatShare(res.data.shareBillId);
          }
        });
      } else {
        alert("请在转由微信进行操作");
      }
    },
    onSubmit() {},
    // Receivablesshow() {
    //   this.flag = !this.flag;
    //   this.getorderlist();
    // },
    router(path) {
      this.$router.push(path);
    },
    setpricesum() {
      if (this.idlist && this.idlist.length > 0) {
        this.pricesum = this.idlist
          .reduce(function(prev, cur) {
            return Number(cur.TotalPrice) + prev;
          }, 0)
          .toFixed(2);
      } else {
        this.pricesum = 0;
      }
    },
    selectitem(good) {

      if (good.selected == false) {
        good.selected = true;
        this.idlist.push(good);
        let is = this.data.h5OrderListDTOS.some(item => {
          return item.selected == false;
        });

        if (is == false) {
          this.checked = true;
        }
        this.setpricesum();
      } else {
        good.selected = false;
        let position = this.idlist.findIndex(item => {
          return item.KaOrderId == good.KaOrderId;
        });

        this.idlist.splice(position, 1);
        this.checked = false;
        this.setpricesum();
      }
    },
    onCancel() {
      // Toast('取消');
    },
    getorderlist() {
      let parm = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        serachTxt: this.serachTxt,
        orderTypes: this.orderTypes,
        payTypes: this.payTypes,
        h5StartDate: this.startDate,
        h5EndDate: this.endDate
      };

      if (this.flag) {
        parm.payMode = true;
      }

      orderlist(parm).then(res => {
        let ids = [];

        if (this.flag && res.data.h5OrderListDTOS.length <= 0) {
          this.$toast(
            "当前搜索状态下，无符合收款条件订单，请确认订单未收款，或已完成对账！"
          );
        } else {
          res.data.h5OrderListDTOS.forEach(item => {
            if (this.idlist && this.idlist.length > 0) {
              ids = this.idlist.map(obj => {
                return obj.KaOrderId;
              });

              item.selected = ids.indexOf(item.KaOrderId) > -1;
            } else {
              item.selected = false;
            }
          });
          res.data.h5OrderListDTOS = Array.from(res.data.h5OrderListDTOS);
          this.data = res.data;
          let is = this.data.h5OrderListDTOS.some(item => {
            return item.selected == false;
          });

          if(this.data.h5OrderListDTOS.length == 0){
            this.checked = false;
          }else{
            this.checked = !is;
          }
          this.pagecount = Math.ceil(res.data.totalCount / this.pageSize);
        }
      });
    },
    onLoad() {
      setTimeout(() => {
        this.num++;
        let parm = {
          currentPage: this.num,
          pageSize: this.pageSize,
          serachTxt: this.serachTxt,
          orderTypes: this.orderTypes,
          payTypes: this.payTypes,
          h5StartDate: this.startDate,
          h5EndDate: this.endDate
        };

        // if (this.flag) {
        //   parm.payMode = true;
        // }
        // if (this.num != 1) {
        //   orderlist(parm).then(res => {
        //     if (this.flag && res.data.h5OrderListDTOS.length <= 0) {
        //       this.$toast(
        //         "当前搜索状态下，无符合收款条件订单，请确认订单未收款，或已完成对账！"
        //       );
        //     } else if (res.data.h5OrderListDTOS.length == 0) {
        //       this.loading = false;
        //       this.finished = true;
        //     } else {
        //       res.data.h5OrderListDTOS.forEach(item => {
        //         item.selected = false;
        //         this.data.h5OrderListDTOS.push(item);
        //       });
        //       this.checked = false;
        //       this.loading = false;
        //     }
        //   });
        // } else {
        //   this.loading = false;
        // }
      }, 1000);
    },
    onRefresh() {
      setTimeout(() => {
        this.num = 0;
        // this.finished = false;
        this.loading = false;
        this.getorderlist();
        this.isLoading = false;
      }, 1000);
    },
    // changpage (val) {
    //   this.currentPage = val;
    //   this.getorderlist();
    // },
    godetail(val) {
      this.$router.push({
        path: "/orderdetail",
        query: { orderId: val, isEdit: 0 }
      });
    },
    add() {
      this.$router.push({
        path: "/shureList"
      });
    },
    changeselectall() {
      if (!this.checked) {
        this.checked = false;
        this.data.h5OrderListDTOS.forEach(item => {
          item.selected = false;
        });
        let arrayone = this.idlist;

        let arraytwo = this.data.h5OrderListDTOS;

        let arr3 = [];

        for (let index = 0; index < arrayone.length; index++) {
          let item = arrayone[index];

          if (!arraytwo.some(v => v.KaOrderId === item.KaOrderId)) {
            arr3.push(item);
          }
        }
        this.idlist = arr3;
        this.setpricesum();
      } else {
        this.checked = true;
        this.data.h5OrderListDTOS.forEach(item => {
          item.selected = true;
        });
         this.idlist = [];
        this.idlist.push.apply(this.idlist, this.data.h5OrderListDTOS);
        this.setpricesum();
      }
    },
    showSearch() {
      this.isshowSearch = true;
    },
    onClickRight() {
      // let url = window.location.host;

      // let index = url.indexOf("pre");

      // if (index <= -1) {
      //   window.location.href = "https://ka.lecarlink.com/index.aspx";
      // } else {
      //   window.location.href = "https://ka-pre.lecarlink.com/index.aspx";
      // }
    },
    Surecarriage(val) {
      this.$router.push({
        path: "/details",
        query: { orderId: val }
      });
    },
    SureError(val) {
      this.$router.push({
        path: "/adjust",
        query: { orderId: val }
      });
    },
    Suremodify(val) {
      this.$router.push({
        path: "/orderdetail",
        query: { orderId: val, isEdit: 1 }
      });
    },
    pay(val) {
      Dialog.confirm({
        message: "请确认该笔订单当前货量和价格准确，是否通知给客户？"
      })
        .then(() => {
          let parm = {
            kaOrderId: val.KaOrderId
          };

          pushOrderNotice(parm).then(res => {
            if (res.code == 200) {
              this.getorderlist();
            }
          });
        })
        .catch(() => {
          // on cancel
        });
    },
    //显示隐藏 筛选项
    showSearchItem() {
      this.IsshowSearchItem = !this.IsshowSearchItem;
    },
    //显示隐藏日历
    ShowCalendar(type) {
      this.defaultDate = new Date();
      this.isShowCalendar = !this.isShowCalendar;
      if(!this.isShowCalendar){
        return;
      }
      this.chooseDateType = type;
      if (type == "endDate") {
        console.log(this.startDate)
        this.minDate = new Date(this.startDate ? this.startDate : "2000-01-01");
      } else {
        console.log(new Date("2000-01-01"))
        this.minDate = new Date("2000-01-01");
        // this.maxDate = new Date();
      }
    },

    //选择筛选项
    pick(type, index) {
      let arr = this[type];

      arr[index].active = !arr[index].active;
      let isAll = index == 0;

      if (index == 0) {
        arr.forEach(item => {
          item.active = false;
        });
        arr[0].active = isAll;
      } else {
        let filterArr = arr.filter(item => {
          return item.active;
        });

        arr[0].active = filterArr.length == 0;
      }
    },
    //点击日期 选择起始  截止日期
    selectDate(date) {
      this[this.chooseDateType] = formatDate(date, "yyyy-MM-dd");
      this.isShowCalendar = false;
      // console.log(formatDate(date,"yyyy-MM-dd"));
    },
    
    //筛选 提交
    confirmSearch() {
      let orderTypes = [];

      let payTypes = [];

      this.orderType.forEach((item, i) => {
        if (item.active && i != 0) {
          orderTypes.push(item.value);
        }
      });

      this.payType.forEach((item, i) => {
        if (item.active && i != 0) {
          payTypes.push(item.value);
        }
      });

      this.orderTypes = orderTypes;
      this.payTypes = payTypes;
      this.currentPage = 1;

      this.getorderlist();
      this.IsshowSearchItem = false;
    },
    clearDate() {
      this.endDate = null;
      this.startDate = null;
    },
    onClickLeft: function() {
      this.$toast("提货列表");
      this.$router.push({
        path: "/pickUpList",
        query: {}
      });
    }
  }
};
</script>
<style>
  .btnes{
    margin-bottom: 20px;
  }
   .btnes img{
     width: 40px;
     height: 40px;
   }
  .van-calendar__selected-day {
    width: 39px!important;
    height: 39px!important;
    border-radius: 50%;
  }
  .van-popup--top{
    overflow: hidden;
  }
</style>
<style lang="scss">
.orderlist {
  width: 100%;
  height: 100%;
  padding-bottom: 60px;
}

.lists {
  // padding: 10px 16px 0 16px;
  padding: 60px 16px 0 16px;
  background: #f8f8f8;
  text-align: center;
}
.count{
  width: 90%;
}
.info .van-cell__value{
  display: flex;
  align-items: center;
}
.info {
  background: #fff;
  padding: 0 14px 10px 14px;
  margin-bottom: 10px;
  position: relative;
  .label {
    font-family: PingFangSC-Regular;
    font-size: 14px;
    text-align: left;
    padding-top: 14px;
    display: flex;
    margin-left: 29px;
    .tit {
      color: #999999;
      width: 73px;
    }
    .con {
      color: #333333;
      flex: 1;
    }
    .coninfo {
      color: #00b578;
      flex: 1;
    }
  }
  .times {
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: #666666;
    text-align: left;
    padding-top: 7px;
  }
}
.van-dialog__confirm,
.van-dialog__confirm:active {
  color: #55A79A;
}
.lsit {
  z-index: 0;
  position: relative;
}
.backgroudimage {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 3000;
  .ims {
    width: 100%;
    height: 100%;
  }
}
.active {
  color: #55A79A !important;
  background: #fff8f4 !important;
  border: 1px solid #55A79A;
}
.van-calendar__header-subtitle {
  height: 24px;
  line-height: 24px;
}
.van-nav-bar__text {
  color: #ff6540;
}
/deep/.van-tabs__wrap,
/deep/.van-hairline--top-bottom {
  position: fixed;
  z-index: 1000;
  top: 43px;
  width: 100%;
}
</style>


